package com.learn.security.oauth2.auth.server.service.security.impl;

import cn.hutool.core.util.ObjectUtil;
import com.learn.security.oauth2.auth.server.config.security.LoginUser;
import com.learn.security.oauth2.auth.server.service.db.service.ISysUserService;
import com.learn.security.oauth2.auth.server.service.security.PermissionsService;
import com.learn.security.oauth2.orm.SysRole;
import com.learn.security.oauth2.orm.SysUser;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 重写加载用户
 *
 * @author knight
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

	/** 系统用户服务 */
	private final ISysUserService sysUserService;

	/** 权限服务 */
	private final PermissionsService permissionsService;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 根据用户名查询用户
		SysUser sysUser = sysUserService.selectUserByUsername(username);
		// 如果用户不存在
		if (ObjectUtil.isNull(sysUser)) {
			throw new UsernameNotFoundException("当前用户名不存在");
		}
		// 查询角色列表
		List<SysRole> sysRoles = permissionsService.selectRoleList(sysUser.getId());
		// 查询权限列表
		Set<String> sysPerms = permissionsService.selectPermSetByRoles(sysRoles);
		// 构建返回值
		return new LoginUser(sysUser, sysRoles.stream().map(SysRole::getSrKey).collect(Collectors.toSet()), sysPerms);
	}

}
